import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { storeToRefs } from 'pinia'
import { getToken } from '@/utils/auth'
import getPageTitle from '@/utils/get-page-title'
import useStore from '@/stores'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const { userStore } = useStore()
  const { info } = storeToRefs(userStore)
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  // 判断token
  if (hasToken) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({ path: '/dashboard' })
    } else if (to.path === '/') {
      next({ path: '/dashboard' })
    } else {
      if (!info.value) {
        await userStore.getUserRoles()
        next({ ...to, replace: true }) //解决刷新空白页
      } else {
        next() //解决刷新空白页
        NProgress.done()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
